/**
 * Created by admin on 2017/5/3.
 * 下载模型
 */
const mysqlUtil = require('../utils/mysql_util');
const squel = require('squel');
const logUtil = require('../utils/log_util');
const _ = require('lodash');


// var mysqlConn = require('./mysqlConn');
const downloadByUrl = require('../utils/downloadByUrl');
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');
const jsonfile = require('jsonfile');

// 下载图片mongodb访问路径
const modelServerMongodbUrl = 'http://192.168.0.8/jmyd-model-obj/';
const modelImageMongodbUrl = 'http://192.168.0.8/jmyd-model-image/';


// 下载图片保存路径
const aimPath = 'E:/model_info/';



/**
 * 根据模型分类编码创建对应的分类目录
 * @param savePath
 * @param typeCode
 */
const createCatalogDir = (savePath, typeCode) => {
  if (typeCode.length > 1) { // 创建一级分类目录
    savePath = `${savePath}/${typeCode.substr(0, 2)}`;
    if (!fs.exists(savePath)) mkdirp.sync(savePath);
  }
  if (typeCode.length > 2) { // 创建二级分类目录
    savePath = `${savePath}/${typeCode.substr(0, 4)}`;
    if (!fs.exists(savePath)) mkdirp.sync(savePath);
  }
  if (typeCode.length > 5) { // 创建三级分类目录
    savePath = `${savePath}/${typeCode.substr(0, 6)}`;
    if (!fs.exists(savePath)) mkdirp.sync(savePath);
  }
  return savePath;
};


exports.downloadModel = async (ctx) => {
  const productIds = ctx.query.mo.toString().split(',');
  mysqlUtil.execute(squel.select().from('model_service.product_model').field('*').where('productId in ?', productIds)
    .toString())
    .then((rows) => {
      const proArr = [];
      rows.forEach((result) => {
        let mongodbUrl = '';
        let imageUrl = '';
        if (result.isFurniture === 1) {
          mongodbUrl = modelServerMongodbUrl;
          imageUrl = modelImageMongodbUrl;
        } else {
          mongodbUrl = homeMaterialsMongodbUrl;
          imageUrl = homeMaterialsMongodbUrl;
        }
        let savePath = aimPath;
        const catalogCode = result.productCode;

        if (catalogCode) {  // 如果分类目录为空，则不予处理
          savePath = createCatalogDir(savePath, catalogCode);
          // 根据模型id创建模型存储文件夹
          const productId = result.productId;
          savePath = `${savePath}/${productId}`;
          if (!fs.exists(savePath)) mkdirp.sync(savePath);


          // 下载缩略图
          const imagesResize = result.imagesResize;
          if (imagesResize) {
            const url = imageUrl + imagesResize; // path.join(mongodbUrl, imagesResize);
            console.log(url);
            if (!fs.exists(path.join(savePath, imagesResize))) {
              proArr.push(downloadByUrl.downloadByUrl(url, imagesResize, savePath));
            }
          }

          // 下载顶视图
          const top = result.top;
          if (top) {
            const url1 = mongodbUrl + top; //  path.join(mongodbUrl, top);
            downloadByUrl.downloadByUrl(url1, top, savePath);
          }

          // 下载纹理图
          const textureUrl = result.textureUrl;
          if (textureUrl) {
            const url2 = mongodbUrl + textureUrl; // path.join(mongodbUrl, textureUrl);
            if (!fs.exists(path.join(savePath, textureUrl))) {
              proArr.push(downloadByUrl.downloadByUrl(url2, textureUrl, savePath));
            }
          }

          // 下载模型
          const modelUrl = result.modelUrl;
          if (modelUrl) {
            const url = mongodbUrl + modelUrl; // path.join(mongodbUrl, textureUrl);
            if (!fs.exists(path.join(savePath, modelUrl))) {
              proArr.push(downloadByUrl.downloadByUrl(url, modelUrl, savePath));
            }
          }

          // 保存当前数据集
          if (!fs.exists(path.join(savePath, 'result.json'))) {
            proArr.push(new Promise((resolve, reject) => {
              const fileName = path.join(savePath, 'result.json');
              jsonfile.writeFile(fileName, result, (jerr) => {
                if (jerr) {
                  console.log(`down fail!  ${fileName}`);
                  reject(`XXXX fail!  ${fileName}`);
                } else {
                  console.log(`down success!  ${fileName}`);
                  resolve(`XXXXX success!  ${fileName}`);
                }
              });
            }));
          }
        }
      });
      Promise.all(proArr).then(() => {
        ctx.body = '成功！';
      }).catch((err) => {
        ctx.body = err.message;
      });
    })
    .catch((err) => {
      throw err;
    });
};

